package hero.mps.web.school_teacher.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import hero.mps.utils.ResultUtils;
import hero.mps.utils.ResultVo;
import hero.mps.web.class_course.entity.ClassCourse;
import hero.mps.web.class_course.entity.ParamVO;
import hero.mps.web.class_course.service.ClassCourseService;
import hero.mps.web.school_class.entity.SchoolClass;
import hero.mps.web.school_class.service.SchoolClassService;
import hero.mps.web.school_student.entity.SchoolStudent;
import hero.mps.web.school_student.service.SchoolStudentService;
import hero.mps.web.school_teacher.entity.ExportStuExcel;
import hero.mps.web.school_teacher.entity.ExportStuParam;
import hero.mps.web.school_teacher.entity.SchoolTeacher;
import hero.mps.web.school_teacher.entity.TeacherParam;
import hero.mps.web.school_teacher.service.SchoolTeacherService;
import hero.mps.web.stu_points.entity.StuPoints;
import hero.mps.web.sys_role.entity.SysRole;
import hero.mps.web.sys_role.service.SysRoleService;
import hero.mps.web.teacher_role.entity.TeacherRole;
import hero.mps.web.teacher_role.service.TeacherRoleService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/teacher")
@RequiredArgsConstructor
public class SchoolTeacherController {
    private final SchoolTeacherService schoolTeacherService;
    private final SysRoleService sysRoleService;
    private final TeacherRoleService teacherRoleService;
    private final ClassCourseService classCourseService;
    private final SchoolClassService schoolClassService;
    private final SchoolStudentService schoolStudentService;


    /**
     * 重置教师密码
     *
     * @param schoolTeacher 包含教师信息的SchoolTeacher对象，其中password字段为待重置的密码（明文）
     */
    @PostMapping("/resetPassword")
    public ResultVo resetPassword(@RequestBody SchoolTeacher schoolTeacher) {
        schoolTeacher.setPassword(DigestUtils.md5DigestAsHex(schoolTeacher.getPassword().getBytes()));
        boolean b = schoolTeacherService.updateById(schoolTeacher);
        if (b) {
            return ResultUtils.success("重置成功");
        }else {
            return ResultUtils.error("重置失败");
        }
    }
    /**
     * 导入学生成绩
     */
    @PostMapping("importStuInfo")
    public ResultVo importStuInfo(@RequestParam("file") MultipartFile file, Integer classId, Integer courseId) throws Exception{
        ImportParams importParams = new ImportParams();
        // 数据处理
        importParams.setHeadRows(1);
        ExcelImportResult<ExportStuExcel> result = ExcelImportUtil.importExcelMore(file.getInputStream(), ExportStuExcel.class, importParams);
        List<ExportStuExcel> list = result.getList();
        ArrayList<StuPoints> stuPointsArrayList = new ArrayList<>();
        if (list.size() == 0) {
            return ResultUtils.error("导入失败,请检查文件格式");
        }
        if (list.size() >= 0) {
            for (int i = 0; i < list.size(); i++) {
                LambdaQueryWrapper<SchoolStudent> queryWrapper = Wrappers.lambdaQuery(SchoolStudent.class)
                        .eq(SchoolStudent::getStuNum, list.get(i).getStuNum());
                SchoolStudent one = schoolStudentService.getOne(queryWrapper);
                if (one != null) {
                    StuPoints stuPoints = new StuPoints();
                    stuPoints.setStuId(one.getStuId());
                    stuPoints.setClassId(classId);
                    stuPoints.setCourseId(courseId);
                    stuPoints.setPoint(list.get(i).getPoints());
                    stuPointsArrayList.add(stuPoints);
                }
            }
        }
        schoolTeacherService.saveStuPoints(stuPointsArrayList, classId, courseId);
        return ResultUtils.success("导入成功");
    }
    /**
     * 导出班级学生信息
     * @param response
     * @param param
     * @return
     * @throws IOException
     */
    @RequestMapping("/exportStuInfo")
    public ResultVo exportStuInfo (HttpServletResponse response, ExportStuParam param) throws IOException {
        // 查询班级信息
        SchoolClass schoolClass = schoolClassService.getById(param.getClassId());
        // 查询班级下的所有学生
        LambdaQueryWrapper<SchoolStudent> queryWrapper = Wrappers.lambdaQuery(SchoolStudent.class).eq(SchoolStudent::getClassId, schoolClass.getClassId());
        List<SchoolStudent> studentList = schoolStudentService.list(queryWrapper);
        ArrayList<ExportStuExcel> list = new ArrayList<>();
        // 导出excel
        for (int i = 0; i < studentList.size(); i++) {
            ExportStuExcel excel = new ExportStuExcel();
            excel.setStuNum(studentList.get(i).getStuNum());
            excel.setStuName(studentList.get(i).getStuName());
//            excel.setPoints(studentList.get(i));
            list.add(excel);
        }
        String fileName = schoolClass.getClassName() + ".xlsx";
        ExportParams exportParams = new ExportParams();
        exportParams.setType(ExcelType.XSSF);
        Workbook sheets = ExcelExportUtil.exportExcel(exportParams, ExportStuExcel.class, list);
        downloadExcel(fileName, sheets, response);
        return ResultUtils.success("导出成功");
    }

    public static void downloadExcel(String fileName, Workbook workbook, HttpServletResponse response) throws IOException {
        try {
            if (StringUtils.isEmpty(fileName)) { // 假设StringUtils是Apache Commons Lang库中的类
                throw new RuntimeException("导出文件名不能为空");
            }

            String encodeFileName = URLEncoder.encode(fileName, "UTF-8");
            response.setHeader("Content-Type", "application/vnd.ms-excel; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + encodeFileName); // 修正filename格式
            response.setHeader("FileName", encodeFileName); // 通常这个header不是标准的，但在某些情况下可能被前端使用
            response.setHeader("Access-Control-Expose-Headers", "FileName"); // 允许跨域访问这个header

            workbook.write(response.getOutputStream()); // 修正方法名为getOutputStream
            workbook.close();
        } catch (Exception e) {
            try {
                workbook.close(); // 确保在异常时关闭Workbook
            } catch (IOException ex) {
                // 可以在这里记录日志或者进行其他异常处理
            }
            throw e; // 重新抛出异常，以便上层可以处理
        }
    }
    /**
     * 编辑教师信息
     * @param schoolTeacher
     * @return
     */
    @PostMapping
    public ResultVo addTeacher(@RequestBody SchoolTeacher schoolTeacher) {
        LambdaQueryWrapper<SchoolTeacher> queryWrapper = Wrappers.lambdaQuery(SchoolTeacher.class)
                .eq(SchoolTeacher::getTeacherNum, schoolTeacher.getTeacherNum());
        SchoolTeacher one = schoolTeacherService.getOne(queryWrapper);
        if (one != null) {
            return ResultUtils.error("教师编号已存在");
        }
        schoolTeacher.setPassword(DigestUtils.md5DigestAsHex(schoolTeacher.getPassword().getBytes()));
        schoolTeacherService.addTeacher(schoolTeacher);
        return ResultUtils.success("新增成功");
    }

    /**
     * 更新教师信息
     * @param schoolTeacher
     * @return
     */
    @PutMapping
    public ResultVo editTeacher(@RequestBody SchoolTeacher schoolTeacher) {
        LambdaQueryWrapper<SchoolTeacher> queryWrapper = Wrappers.lambdaQuery(SchoolTeacher.class)
                .eq(SchoolTeacher::getTeacherNum, schoolTeacher.getTeacherNum());
        SchoolTeacher one = schoolTeacherService.getOne(queryWrapper);
        if (one != null && !one.getTeacherId().equals(schoolTeacher.getTeacherId())) {
            return ResultUtils.error("教师编号已存在");
        }
        schoolTeacher.setPassword(DigestUtils.md5DigestAsHex(schoolTeacher.getPassword().getBytes()));
        schoolTeacherService.editTeacher(schoolTeacher);
        return ResultUtils.success("编辑成功");
    }

    /**
     * 删除教师
     * @param teacherId
     * @return
     */
    @DeleteMapping("/{teacherId}")
    public ResultVo deleteTeacher(@PathVariable("teacherId") Integer teacherId) {
        schoolTeacherService.deleteTeacher(teacherId);
        return ResultUtils.success("删除成功");
    }

    /**
     * 搜索查询教师列表
     * @param teacherParam
     * @return
     */
    @GetMapping("/list")
    public ResultVo list(TeacherParam teacherParam) {
//        构建分页对象
        IPage<SchoolTeacher> page = new Page(teacherParam.getCurrentPage(), teacherParam.getPageSize());
//        构建查询条件
        QueryWrapper<SchoolTeacher> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(teacherParam.getTeacherName())) {
            queryWrapper.lambda().like(SchoolTeacher::getTeacherName, teacherParam.getTeacherName());
        }
        IPage<SchoolTeacher> iPage = schoolTeacherService.page(page, queryWrapper);
        return ResultUtils.success("查询成功", iPage);
    }

    /**
     * 获取教师班级课程信息
     * @param param
     * @return
     */
    @GetMapping("/getTeacherClassCourseList")
    public ResultVo getTeacherClassCourseList(ParamVO param){
        IPage<ClassCourse> classCourseList = classCourseService.getTeacherClassCourseList(param);
        return ResultUtils.success("查询成功", classCourseList);
    }

    /**
     * 查询教师列表
     * @return
     */
    @GetMapping("/getList")
    public ResultVo getList() {
        List<SchoolTeacher> list = schoolTeacherService.list();
        return ResultUtils.success("查询成功", list);
    }

    /**
     * 查询角色列表
     * @return
     */
    @GetMapping("/getRoles")
    public ResultVo getRoles() {
        LambdaQueryWrapper<SysRole> queryWrapper = Wrappers.lambdaQuery(SysRole.class).ne(SysRole::getRoleType, "2");
        List<SysRole> list = sysRoleService.list(queryWrapper);
        return ResultUtils.success("查询成功", list);
    }

    @GetMapping("/getRoleById")
    public ResultVo getRoleById(Integer teacherId) {
        LambdaQueryWrapper<TeacherRole> queryWrapper = Wrappers.lambdaQuery(TeacherRole.class)
                .eq(TeacherRole::getTeacherId, teacherId);
        TeacherRole one = teacherRoleService.getOne(queryWrapper);
        return ResultUtils.success("查询成功", one);
    }

}
